const SMSClient = require('@alicloud/sms-sdk');
const moment = require('moment');
const log4js = require('../../../utils/log4js');

const sms = module.exports;


const smsClient = new SMSClient({
    accessKeyId: configure.get('storage').oss.accessKeyId,
    secretAccessKey: configure.get('storage').oss.accessKeySecret
});

// 创建短信验证码
sms.crate = async (mobile) => {
    if (!_.trim(mobile)) throw new Error('手机号不能为空');
    if (!helper.isCellPhone(mobile)) throw new Error('手机号格式不正确');

    // 发送短信
    const code = String(Math.floor(Math.random() * 10000000000000000)).substr(0, 6);
    const templateParam = `{"code":${code}}`;
    const sendSMSResult = await smsClient.sendSMS({
        PhoneNumbers: mobile,
        SignName: '亚太名典短信验证',
        TemplateCode: 'SMS_142060196',
        TemplateParam: templateParam
    });

    log4js.debug(sendSMSResult);

    // todo 限流策略

    // 创建数据库记录
    await db().md_sms.create({
        id: helper.uuid(mobile),
        mobile: mobile,
        sms_code: code,
    });

    return true;
};


// 短信验证码校验
sms.check = async (mobile, code) => {
    if (!helper.isCellPhone(mobile)) throw new Error('手机号格式不正确');

    let smsInfo = await helper.getRow(db().md_sms, {
        mobile: mobile,
        sms_code: code,
        status: 0
    }, [['create_time', 'desc']]);
    if (!smsInfo) throw new Error('无效验证码');
    if (moment().diff(moment(smsInfo.create_time), 'minutes') > 15) throw new Error('验证码已过期,请重新发送');

    if (smsInfo.sms_code === code) {
        return true;
    } else {
        throw new Error('验证码无效')
    }
};

// 短信验验证成功后失效
sms.destroy = async (mobile, code) => {
    return await db().md_sms.update({status: 1}, {where: {mobile: mobile, sms_code: code}})
};

// 发送订单或服务通知短信
sms.sendNotice = async (data ={}, type=0) => {
    if(!data.mobile) return true;

    let tpl = '';
    if(type) {
        tpl = 'SMS_165381360';
    } else {
        tpl = 'SMS_157281952'
    }

    const templateParam = {
        nickname:data.nickname,
        brand_name: data.brand_name,
        title: data.title,
        flow_no: data.flow_no,
        total_price: data.total_price,
    };
    const sendSMSResult = await smsClient.sendSMS({
        PhoneNumbers: data.mobile,
        SignName: '亚太名典短信通知',
        TemplateCode: tpl,
        TemplateParam: JSON.stringify(templateParam)
    });

    log4js.debug(sendSMSResult);

    return true;
};

// 发送需求通知短信
sms.sendNoticeDemand = async (data ={}, type=0) => {
    if(!data.mobile) return true;

    let tpl = '';
    let templateParam = {};
    if(type) {
        templateParam = {
            nickname:data.nickname || '',
            type: data.type || '',
            content: data.content || '',
        };
        tpl = 'SMS_165381490';
    } else {
        templateParam = {
            nickname:data.nickname || '',
        };
        tpl = 'SMS_165386470'
    }


    const sendSMSResult = await smsClient.sendSMS({
        PhoneNumbers: data.mobile,
        SignName: '亚太名典短信通知',
        TemplateCode: tpl,
        TemplateParam: JSON.stringify(templateParam)
    });

    log4js.debug(sendSMSResult);

    return true;
};




